package io.gitee.kotle.demo.mvvm_demo.pic

import androidx.lifecycle.viewModelScope
import io.gitee.kotle.android.delegate.unsafeLazy
import io.gitee.kotle.android.mvvm.MvvmViewModel
import io.gitee.kotle.android.utils.*
import kotlinx.coroutines.launch
import okhttp3.Response
import okhttp3.ResponseBody

/**
 *
 * 描述：
 *
 * 创建人：jiale.wei
 * 创建时间：2021/11/22 10:48 上午
 *
 */
class PicViewModel : MvvmViewModel() {

    val picData by unsafeLazy { pageHelperData<Any>() }

    //tags
    //壁纸分类，默认为:0
    //
    //当前可用分类
    //0: 随机
    //1: 4K专区
    //2: 美女模特
    //3: 爱情美图
    //4: 风景大片
    //5: 小清新
    //6: 动漫卡通
    //7: 明星风尚
    //8: 萌宠动物
    //9: 游戏壁纸
    //10: 汽车天下
    //11: 炫酷时尚
    //12: 月历壁纸
    //13: 影视剧照
    //14: 节日美图
    //15: 军事天地
    //16: 劲爆体育
    //17: BABY秀
    //18: 文字控
    //start
    //在 360 壁纸库中，从第几张开始，默认为:0
    //
    //count
    //在json下输出的壁纸数量，默认为:1
    //
    //size
    //只对head下有影响，作用为输出的壁纸分辨率，默认为:0
    //0: 原始尺寸
    //1: 2560x1600
    //2: 1440x900
    //3: 1024x768
    //4: 800x600
    fun loadPic() {
        picData.runOnScope {
            val start = picData.data?.currentPageData?.asOrNull<Int>() ?: 0
            val pageCount = 20
            val datas = mutableListOf<Any>()
            val url =
                "http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=${pageCount}"
            val resultStr = url.awaitHttp<String>()
            val result = resultStr.formJsonString<PicBean>().images
            result?.let {
                datas.addAll(it)
                datas.addAll(it)
                datas.addAll(it)
                datas.addAll(it)
                datas.addAll(it)
            }
            val hasNext = !result.isNullOrEmpty() && result.count() == pageCount
            val data = picData.updatePageHelper(
                start,
                datas,
                start == 0,
                false,
                start + (result?.count() ?: 0)
            )
            data
        }
    }
}